package com.yw.mq.example.m03_order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

import static com.yw.mq.core.MqConstant.DEFAULT_PRODUCER_GROUP;
import static com.yw.mq.core.MqConstant.NAME_SERVER_ADDR;

public class Producer {
    public static void main(String[] args) throws Exception {

        //  创建生产者
        DefaultMQProducer producer = new DefaultMQProducer(DEFAULT_PRODUCER_GROUP);
        // 设置连接信息
        producer.setNamesrvAddr(NAME_SERVER_ADDR);
        // 启动
        producer.start();

        for (int i = 0; i < 10; i++) {

            Message message = new Message();
            message.setKeys(IdUtil.getSnowflakeNextIdStr());
            message.setTopic("order_topic");
            message.setTags("food");
            message.setBody(("hello mq" + i).getBytes());

            SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    // 根据条件，例如订单号等，计算一个下标，从而都取同一个队列
                    return list.get(0);
                }
            }, null);

            System.out.println("发送消息结果：" + sendResult);
        }

        producer.shutdown();
    }
}
